package com.zzq.mq;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @author iszengziqiang@163.com
 * @date 2020/10/22 16:46
 * @Version: 1.0
 * @desc //todo
 */
@Component
public class RocketmqProducer {


    //同步发送消息
    public void SyncProducer(String msgBody) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {
        //Instantiate with a producer group name.
        DefaultMQProducer producer = new
                DefaultMQProducer("SyncProducer-group");
        // Specify name server addresses.
        producer.setNamesrvAddr("192.168.98.129:9876");
        //Launch the instance.
        producer.start();
        for (int i = 0; i < 100; i++) {
            //Create a message instance, specifying topic, tag and message body.
            Message msg = new Message("SyncProducer-topic" /* Topic */,
                    "TagA" /* Tag */,
                    (msgBody + "##" + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );
            //Call send message to deliver message to one of brokers.
            SendResult sendResult = producer.send(msg);
            System.out.printf("返回值：" + sendResult.toString());
        }
        //Shut down once the producer instance is not longer in use.
        producer.shutdown();
    }

}
